package com.zxj.camerademo.camera1;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.RectF;
import android.hardware.Camera;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import com.zxj.camerademo.R;
import com.zxj.camerademo.utils.BitmapUtils;
import com.zxj.camerademo.utils.FileUtil;
import com.zxj.camerademo.view.FaceView;

import java.io.File;
import java.util.ArrayList;

import okio.Okio;

public class CameraActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = CameraActivity.class.getCanonicalName();

    public static String TYPE_TAG = "type";
    public static int TYPE_CAPTURE = 0;
    public static int TYPE_RECORD = 1;
    private CameraHelper mCameraHelper;
    private MediaRecorderHelper mMediaRecorderHelper;
    private boolean lock = false; //控制MediaRecorderHelper的初始化

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

        SurfaceView surfaceView = findViewById(R.id.surfaceView);
        final FaceView faceView = findViewById(R.id.faceView);
        final ImageButton btnTakePic = findViewById(R.id.btnTakePic);
        final ImageView btnStart = findViewById(R.id.btnStart);
        final ImageView ivExchange = findViewById(R.id.ivExchange);
        final ImageView btnStop = findViewById(R.id.btnStop);

        mCameraHelper = new CameraHelper(this, surfaceView);
        mCameraHelper.addCallBack(new CameraHelper.CallBack() {
            @Override
            public void onPreviewFrame(byte[] data) {
                if (!lock) {
//                    Camera camera = mCameraHelper.getCamera();
                    mMediaRecorderHelper = new MediaRecorderHelper(CameraActivity.this, mCameraHelper.getCamera(),
                            mCameraHelper.mDisplayOrientation, mCameraHelper.mSurfaceHolder.getSurface());
                    lock = true;
                }
            }

            @Override
            public void onTakePic(byte[] data) {
                savePic(data);
                btnTakePic.setClickable(true);
            }

            @Override
            public void onFaceDetect(ArrayList<RectF> faces) {
                faceView.setFaces(faces);
            }
        });

        if(getIntent().getIntExtra(TYPE_TAG,0) == TYPE_RECORD){
            btnTakePic.setVisibility(View.GONE);
            btnStart.setVisibility(View.VISIBLE);
        }

        btnTakePic.setOnClickListener(this);
        ivExchange.setOnClickListener(this);
        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ivExchange.setClickable(false);
                btnStart.setVisibility(View.GONE);
                btnStop.setVisibility(View.VISIBLE);
                Log.e("zxj","btnStart---mMediaRecorderHelper="+mMediaRecorderHelper);
                if(mMediaRecorderHelper != null)
                    mMediaRecorderHelper.startRecord();
            }
        });

        btnStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btnStart.setVisibility(View.VISIBLE);
                btnStop.setVisibility(View.GONE);
                ivExchange.setClickable(true);
                if(mMediaRecorderHelper != null)
                    mMediaRecorderHelper.stopRecord();
            }
        });
    }

    //保存照片
    private void savePic(final byte[] data) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                final long temp = System.currentTimeMillis();
                final File picFile = FileUtil.createCameraFile("camera1");
                if (picFile != null && data != null) {
                    Bitmap rawBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                    Bitmap resultBitmap;
                    if (mCameraHelper.mCameraFacing == Camera.CameraInfo.CAMERA_FACING_FRONT){
                        resultBitmap = BitmapUtils.mirror(BitmapUtils.rotate(rawBitmap, 270f));//前置摄像头旋转270°
                    }else {
                        resultBitmap = BitmapUtils.rotate(rawBitmap, 90f);//后置摄像头旋转90°
                    }

                    try {
                        Okio.buffer(Okio.sink(picFile)).write(BitmapUtils.toByteArray(resultBitmap)).close();
                        CameraActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(CameraActivity.this,"图片已保存！"+picFile.getAbsolutePath(),Toast.LENGTH_SHORT).show();
                                Log.d(TAG,"图片已保存! 耗时：" + (System.currentTimeMillis() - temp) + "  路径： "+picFile.getAbsolutePath());
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                        CameraActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(CameraActivity.this,"保存图片失败！",Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            }
        }).start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCameraHelper.releaseCamera();
        if(mMediaRecorderHelper != null) {
            mMediaRecorderHelper.stopRecord();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btnTakePic:
                mCameraHelper.takePic();
                break;
            case R.id.ivExchange:
                mCameraHelper.exchangeCamera();
                break;
        }
    }
}
